<template>
  <div class="plan-dialog">
    <el-dialog :visible.sync="visible">
      <div class="plan-container">
        <div class="panelWrap plan-content">
          <div class="title flex flexac flexjcsb fs14 cfff fwb pl p-r-20">
            <div>{{ isEdit ? '修改维保评价' : '添加维保评价' }}</div>
            <i class="el-icon-close" @click="handleCloseDialog" />
          </div>
          <div class="plan-main flex flexdc flexcenter m-t-30">
            <div>
              <!-- top合同内容 -->
              <div class="main-cont flex">
                <div class="cont-left">
                  <div class="entryName m-b-20">
                    <span class="name"><span class="mustval">*</span>维保合同：</span>
                    <el-input v-model="form.contractNumbe" readonly class="entry-input co-input" placeholder="请选择维保合同" />
                    <el-button v-if="form.state === '已发起'" type="warning" class="m-l-10" @click="handleContrat">选择合同</el-button>
                  </div>
                  <div class="demand m-b-20">
                    <span class="name"><span class="mustval">*</span>计划名称：</span>
                    <el-input v-model="form.name" class="co-input" placeholder="请输入计划名称" />
                  </div>
                  <div class="maType m-b-20">
                    <span class="name"><span class="mustval">*</span>维保方式：</span>
                    <el-select v-model="form.type" placeholder="请选择维保方式" class="co-input">
                      <el-option
                        v-for="item in typeOptions"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      />
                    </el-select>
                  </div>
                </div>
                <div class="con-right flex flexdc">
                  <div class="creDate co-date m-b-20">
                    <span class="name">&nbsp;&nbsp;&nbsp;<span class="mustval">*</span>预约时间：</span>
                    <el-date-picker
                      v-model="form.appointmentDate"
                      type="date"
                      placeholder="选择预约日期"
                    />
                  </div>
                  <div class="co-date lasDate m-b-20">
                    <span class="name"><span class="mustval">*</span>应完成时间：</span>
                    <el-date-picker
                      v-model="form.exceptDate"
                      type="date"
                      placeholder="选择应完成日期"
                    />
                  </div>
                </div>
              </div>
              <!-- 分割线 -->
              <el-divider>电梯选择面板</el-divider>

              <!-- 电梯选择面板 -->
              <div class="m-t-50 flex flexdc flexcenter">
                <!-- 电梯查询条件 -->
                <div class="flex">
                  <div class="elev-left m-r-100">
                    <div class="entryName m-b-20">
                      <span class="name">电梯注册代码：</span>
                      <el-input v-model="param.registerCode" class="entry-input co-input" placeholder="请输入电梯注册代码" />
                    </div>
                    <div class="entryName m-b-20">
                      <span class="code-name">位置码：</span>
                      <el-input v-model="param.rescueCode" class="entry-input co-input" placeholder="请输入位置码" />
                    </div>
                  </div>
                  <div class="elev-right m-l-30">
                    <div class="entryName m-b-20">
                      <span class="name">维保单位：</span>
                      <el-input v-model="param.maintenanceUnitName" readonly class="entry-input" placeholder="请选择维保单位" />
                      <el-button type="warning" class="unitbtn m-l-10" @click="handleSelectUnit(0)">选择单位</el-button>
                    </div>
                    <div class="entryName m-b-20">
                      <span class="name">使用单位：</span>
                      <el-input v-model="param.useUnitName" readonly class="entry-input" placeholder="请选择使用单位" />
                      <el-button type="warning" class="unitbtn m-l-10" @click="handleSelectUnit(1)">选择单位</el-button>
                    </div>
                  </div>
                </div>
                <div class="flex m-t-20">
                  <el-button
                    class="flex flexac m-r-20 fs14"
                    size="small"
                    type="warning"
                    @click="getElevatorList(
                      {
                        registerCode: param.registerCode,
                        rescueCode: param.rescueCode,
                        maintenanceUnitName: param.maintenanceUnitName,
                        useUnitName: param.useUnitName
                      }
                    )"
                  ><i class="co-i" /><span class="search1">查 询</span></el-button>
                  <el-button class="co-empty flexcenter m-l-25" type="info" @click="handleEmptySearch"><i class="iconfont icon-qingkong" />清 空</el-button>
                </div>
                <!-- 电梯列表 -->
                <el-table
                  ref="multipleTable"
                  class="m-t-30 con-table m-b-25"
                  type="expand"
                  :data="dataList.slice((paging.currentPage - 1) * paging.pageSize, paging.currentPage * paging.pageSize)"
                  highlight-current-row
                  :row-key="getRowKey"
                  @select-all="handleCheck"
                  @select="handleCheck"
                  @selection-change="handleCheckChange"
                >
                  <!-- 复选框 -->
                  <el-table-column type="selection" width="55" height="40" />

                  <template v-for="item in tablehead">
                    <el-table-column :key="item.id" :width="item.width" align="center" :prop="item.prop" :label="item.label" />
                  </template>

                  <el-table-column align="center" label="绑定状态" width="100">
                    <template slot-scope="scope">
                      <span :class="`status-${scope.row.bindState}`">
                        {{
                          scope.row.bindState === 0 ? '未绑定' :
                          scope.row.bindState === 1 ? '已录入' :
                          scope.row.bindState === 2 ? '已申请' :
                          scope.row.bindState === 3 ? '已绑定' :
                          scope.row.bindState === 4 ? '已拒绝' : '未确认'
                        }}
                      </span>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
              <el-pagination class="paginationWrap flex " :current-page="paging.currentPage" :page-sizes="paging.pageSizeArr" :page-size="paging.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="paging.total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
            </div>

            <div class="flex footer m-t-10 m-b-20">
              <el-button v-if="!isEdit" class="saveBtn btn m-r-30 el-icon-circle-check" @click="handleSave(0)">保 存</el-button>
              <el-button v-else type="success" class="m-r-30 btn el-icon-circle-check" @click="handleSave(1)">更 新</el-button>
              <el-button class="clsoeBtn btn el-icon-circle-close" @click="handleCloseDialog">关 闭</el-button>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>
    <PlanCont v-model="conVisible" @update="handleConUpdate" @updates="handleConUpdates" @handleCloseDialog="handleClosePCDialog" />
    <UserUnit v-model="unitVisible" @update="handleUnitUpdate" @update1="handleMaUpdate" />
  </div>
</template>

<script>

import UserUnit from '@/components/userUnit/index'
import PlanCont from './planCont'
import { showNotice } from '@/utils/toolclass'
import { miPlanAdd, miPlanUpdate } from '@/api/maintenance/plan'
import { elevatorQueryList } from '@/api/elevator/elevator'
import bus from '@/utils/bus'

export default {
  components: { PlanCont, UserUnit },
  props: {
    isEdit: {
      type: Boolean,
      default: false
    },
    value: {
      type: Boolean,
      default: false
    },
    data: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      visible: false,
      conVisible: false,
      unitVisible: false,
      creValue: '',
      lasValue: '',
      maValue: '',
      dataList: [],
      elevatorList: [],
      originList: [],
      typeOptions: [
        {
          value: '1',
          label: '按需维保'
        },
        {
          value: '2',
          label: '季度维保'
        },
        {
          value: '3',
          label: '半年维保'
        }
      ],
      catValue: '',
      tablehead: [
        {
          index: 0,
          prop: 'registerCode',
          label: '电梯注册代码',
          sortable: false,
          fixed: true,
          isShow: true
        },
        {
          index: 1,
          prop: 'rescueCode',
          label: '位置码',
          width: '100',
          sortable: false,
          fixed: true,
          isShow: true
        },
        {
          index: 2,
          prop: 'usePlaceName',
          label: '使用场所',
          sortable: false,
          fixed: true,
          isShow: true
        },
        {
          index: 3,
          prop: 'maintenanceUnitName',
          label: '维保单位',
          sortable: false,
          fixed: true,
          isShow: true
        },
        {
          index: 4,
          prop: 'useUnitName',
          label: '使用单位',
          sortable: false,
          fixed: true,
          isShow: true
        }
      ],
      form: { ...this.data },
      formOrigin: {
        crtDate: '', // 创建时间
        crtOpr: '', // 创建人
        id: 0, // ID
        lstEdtDate: '', // 最后修改时间
        lstEdtOpr: '', // 最后修改人ID
        orderId: '', // 工单Id
        orgId: '', // 机构id
        otherDesc: '', // 其他建议
        score: '', // 分数
        servicesQuality: '', // 服务质量
        servicesState: '', // 服务态度
        version: '' // 版本号
      },
      paging: {
        currentPage: 1,
        pageSize: 4,
        pageSizeArr: [4, 8, 10, 14],
        total: 0
      },
      param: {
        bindState: '',
        id: '',
        registerCode: '',
        registerUnit: '',
        rescueCode: '',
        maintenanceUnitName: '',
        maintenanceUnitId: '',
        useUnitName: '',
        useUnitId: ''
      }
    }
  },
  watch: {
    visible(v) {
      this.$emit('input', v)
    },
    value(v) {
      this.visible = v
    },
    data(v) {
      if (v.id === 0) {
        this.form = { ...this.formOrigin }
      } else {
        // console.log(v)
        this.form = { ...v }
        // this.dataList = [...v.elevList]
        // console.log(this.elevatorList)

        this.$nextTick(res => {
          v.elevList.map(item => {
            this.$refs.multipleTable.toggleRowSelection(item, true)
          })
          this.dataList = [...v.elevList]
        })
      }
    }
  },
  created() {},
  mounted() {
    this.getElevaList()
  },
  methods: {
    getRowKey(row) {
      return row.id
    },
    handleSelectUnit(type) {
      if (!(/^\S+$/.test(this.form.contractNumbe))) {
        showNotice('error', '提示', '请先选择合同后再查询')
        return
      }
      bus.$emit('type', type)
      this.unitVisible = true
    },
    handleUnitUpdate(row) {
      this.param.useUnitId = row.id
      this.param.useUnitName = row.nameSimple
      // console.log(row)
    },
    // 合同回调更新
    handleConUpdate(row) {
      this.form.contractNumbe = row.contractNumbe
      this.form.contractId = row.id
      // console.log(row)
    },
    // 电梯信息回调更新
    handleConUpdates(rows) {
      this.originList = rows
      this.dataList = rows
      this.paging.total = rows.length
      // console.log(rows)
    },
    handleContrat() {
      this.conVisible = true
    },
    handleMaUpdate(row) {
      // console.log(row)
      this.param.maintenanceUnitId = row.id
      this.param.maintenanceUnitName = row.nameSimple
    },
    handleSave(types) {
      // console.log(this.form.contractId)
      const params = {
        appointmentDate: this.$moment(this.form.appointmentDate).format('YYYY-MM-DD h:mm:ss'), // 预约时间
        contractId: this.form.contractId,	// 合同id
        contractNumbe: this.form.contractNumbe, // 合同编号
        crtDate: this.form.crtDate, // 创建时间
        crtOpr: this.form.crtOpr, // 创建人
        elevatorId: this.selectioned.id,	// 电梯id
        exceptDate: this.$moment(this.form.exceptDate).format('YYYY-MM-DD h:mm:ss'), // 应完成时间
        finishDate: this.form.finishDate, // 完成时间
        id: this.form.id,
        lstEdtDate: this.form.lstEdtDate, // 最后修改时间
        lstEdtOpr: this.form.lstEdtOpr, // 最后修改人ID
        name: this.form.name, // 计划名字(小区名称+年月+电梯维保类型)
        orgId: this.form.orgId, // 机构id
        registerCode: this.form.registerCode, // 电梯注册码
        rescueCode: this.form.rescueCode, // 电梯求援代码
        state: this.form.state === '已发起' ? 1 : this.form.state === '接受' ? 2 : 3, // 计划状态( 1 已发起 2 接受 3 停用)
        type: this.form.type === '按需维保' ? 1 : this.form.type === '季度维保' ? 2 : 3, // 维保类型（定期维保就是：半月维保、季度维保、半年、年度维保，如果是按需维保就是：不定期维保）
        version: this.form.version ? this.form.version : 1 // 版本号
      }
      // console.log(params)
      if (types === 0) {
        this.handleCreate(params)
      } else {
        this.handleUpdate(params)
      }
    },
    handleCreate(data) {
      miPlanAdd(data).then(res => {
        if (res.code === '000000') {
          showNotice('success', '提示', '添加成功')
          this.$emit('handleRefresh')
          this.$emit('handleCloseDialog')
        } else {
          if (res.code === '失败') {
            showNotice('error', '提示', '添加失败')
          } else {
            // showNotice('error', '提示', res.msg)
          }
        }
      })
    },
    handleUpdate(data) {
      miPlanUpdate(data).then(res => {
        if (res.code === '000000') {
          showNotice('success', '提示', '更新成功')
          this.$emit('handleRefresh')
          this.$emit('handleCloseDialog')
        } else {
          if (res.code === '失败') {
            showNotice('error', '提示', '更新失败')
          } else {
            // showNotice('error', '提示', res.msg)
          }
        }
      })
    },
    handleCloseDialog() {
      this.visible = !this.visible
    },
    getElevatorList(params) {
      this.dataList = this.dataList.filter(item => {
        // console.log(item)
        if (
          item.rescueCode === params.rescueCode ||
          item.registerCode === params.registerCode ||
          item.maintenanceUnitName === params.maintenanceUnitName ||
          item.useUnitName === params.useUnitName
        ) {
          return item
        }
      })
      // console.log(params)
    },
    getElevaList() {
      elevatorQueryList('', '', '', 1, 100000, '', '', '', '').then(res => {
        if (res.code === '000000') {
          // console.log(res)
          this.elevatorList = res.data
        }
      })
    },
    // 单选操作，全选按钮失效操作
    handleCheck(selection, row) {
      this.$refs.multipleTable.clearSelection()
      if (selection.length === 0) { // 判断selection是否有值存在
        return
      }
      if (row) {
        this.selectioned = row
        this.$refs.multipleTable.toggleRowSelection(row, true)
      }
    },

    // 取消单选的checkbox
    handleCheckChange(row) {
      if (row.length === 0) {
        this.selectioned = null
      }
    },
    handleEmptySearch() {
      this.param.registerCode = ''
      this.param.rescueCode = ''
      this.param.maintenanceUnitId = ''
      this.param.maintenanceUnitName = ''
      this.param.useUnitId = ''
      this.param.useUnitName = ''
      this.dataList = [...this.originList]
    },
    handleClosePCDialog() {
      this.conVisible = !this.conVisible
    },
    handleSizeChange(val) {
      this.paging.pageSize = val
      this.getContList()
    },
    handleCurrentChange(val) {
      this.paging.currentPage = val
      this.getContList()
    }
  }
}
</script>

<style rel='stylesheet/scss' lang='scss'>
@import "@/styles/public.scss";
.plan-dialog {
  .plan-container {
    margin-top: -130px;
    width: 1000px;
    background: #ffffff;
    margin-left: -200px;
    .plan-content {
      min-height: 560px;
      .plan-main {
        .code-name {
          margin-left: 40px;
        }
        .co-date {
          margin-left: 28px;
        }
        .creDate {
          margin-left: 31px;
        }
        .main-cont {
          justify-content: center;
          .con-right {
            width: 360px;

          }
          .con-left {
          }
        }
        .status-0 {
          color: red;
          font-size: 16px;
          font-weight: 700;
        }
        .status-1 {
          color: darkgoldenrod;
          font-size: 16px;
          font-weight: 700;
        }
        .status-2 {
          color: blue;
          font-size: 16px;
          font-weight: 700;
        }
        .status-3 {
          font-size: 16px;
          font-weight: 700;
        }
        .status-4 {
          font-size: 16px;
          font-weight: 700;
        }
        .status-5 {
          font-size: 16px;
          font-weight: 700;
        }
      }
      .footer {
        .btn {
          height: 40px;
        }
      }
    }
  }
}
</style>
